// pages/addressInfo/addressInfo.ts
import api from "../../utils/api"
import animationHelper from '../../utils/animation';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isDefault: false as boolean,//开启默认地址
    name: '' as string,//姓名
    phone: '' as string,//电话
    districtVal: {} as DistrictModel,//所在地址
    districtValTemp: {} as DistrictModel,//所选择的最低级县级的ID临时
    provinces: [] as DistrictModel[],//省
    cities: [] as DistrictModel[],//市
    districts: [] as DistrictModel[],//区
    strees: [] as DistrictModel[],//街道
    address: '' as string,//页面展示的所在地址
    addressTemp: '' as string,//临时地址
    detailAddress: "" as string,//详细地址
    showAddress: false as boolean,//展示地址弹窗
    value: [0, 0, 0, 0] as Array<number>,//代表默认索引
    valueTemp: [0, 0, 0, 0] as Array<number>,//存储临时value
    animation: null as WechatMiniprogram.Animation | null,
    animationData: {} as any,
    isLoading: false as boolean,//是否正在请求数据
    type: "add" as string,//编辑 or 新建
    id: undefined as number | undefined,//编辑的Id
  },
  // 切换是否为默认地址
  switchChange(): void {
    this.setData({
      isDefault: !this.data.isDefault
    })
  },
  // 输入name
  handleName(e: any): void {
    this.setData({
      name: e.detail.value
    })
  },
  handlePhone(e: any): void {
    this.setData({
      phone: e.detail.value
    })
  },
  handleAddress(e: any): void {
    this.setData({
      detailAddress: e.detail.value
    })
  },
  // 新增地址
  saveAddress(): void {
    const params = {
      name: this.data.name,
      phone: this.data.phone,
      detailAddress: this.data.detailAddress,
      isDefault: this.data.isDefault,
      districtId: this.data.districtVal.id
    } as AddressParam
    if (this.data.type == "add") {
      api.address.addAddress(params).then(res => {
        if (res.data.code == '000') {
          wx.navigateBack();
        } else {
          wx.showToast({
            title: res.data.message as string,
            icon: 'error',
            duration: 2000
          })
          console.error(res.data.message);
        }
      })
    } else if (this.data.type == "edit") {
      params.id = this.data.id
      wx.showModal({
        title: '提示',
        content: "确认修改吗？",
        success: (res) => {
          // 点击确定
          if (res.confirm) {
            // 是默认地址
            if (this.data.isDefault) {
              Promise.all([
                api.address.makeDefault({ id: params.id }),
                api.address.editAddress(params)
              ]).then(([defaultRes, editRes]) => {
                if (defaultRes.data.code == '000' && editRes.data.code == "000") {
                  wx.showToast({
                    title: '修改成功',
                  })
                  setTimeout(() => {
                    wx.navigateBack();
                  }, 1500)
                } else {
                  wx.showToast({
                    title: "修改失败",
                    icon: 'error',
                    duration: 2000
                  })
                }
              }).catch(error => {
                wx.showToast({
                  title: '修改失败',
                  icon: "error",
                })
              })
            } else {
              api.address.editAddress(params).then(res => {
                if (res.data.code == '000') {
                  wx.showToast({
                    title: '修改成功',
                  })
                  setTimeout(() => {
                    wx.navigateBack();
                  }, 1500)
                } else {
                  wx.showToast({
                    title: res.data.message as string,
                    icon: 'error',
                    duration: 2000
                  })
                }
              })
            }
          }
        }
      })
    }

  },
  // dialog中获取地区
  async getArea(type: string, parentId?: number): Promise<void> {
    try {
      this.setData({
        isLoading: true
      })
      const res = await api.district.getDistricts({ parentId })
      this.setData({
        isLoading: false
      })
      if (res.data.code == '000') {
        if (type == 'city') {
          this.setData({
            cities: res.data.data
          })
          if (res.data.data && res.data.data.length > 0) {
            await this.getArea('dis', res.data.data[0].id)
          } else {
            this.setData({
              districts: [],
              strees: []
            })
          }
        } else if (type == 'dis') {
          this.setData({
            districts: res.data.data
          })
          if (res.data.data && res.data.data.length > 0) {
            await this.getArea('stree', res.data.data[0].id)
          } else {
            this.setData({
              strees: []
            })
          }
        } else if (type == 'stree') {
          this.setData({
            strees: res.data.data
          })
        }
      } else {
        wx.showToast({
          title:res.data.message as string,
          icon:'error',
          duration: 2000
        })
        console.error(res.data.message)
      }
    } catch (error) {
      console.error('Error occurred while fetching districts:', error);
    }
  },
  // 展示弹窗
  showAddress(): void {
    const animation = animationHelper.createAnimation(500, 'ease');
    this.setData({ animation: animation });
    animationHelper.showAnimation(animation, 450, this.setData.bind(this), "showAddress");
    // 初始化一个数据
    this.setData({
      addressTemp: this.data.address == '' ? this.data.provinces[0].name + this.data.cities[0].name! + this.data.districts[0].name + this.data.strees[0].name : this.data.address,
      districtValTemp: Object.keys(this.data.districtVal).length ? this.data.districtVal : this.data.strees[0],
      valueTemp: this.data.value
    })
  },
  closeAddress(): void {
    const animation = this.data.animation;
    animationHelper.closeAnimation(animation, 450, this.setData.bind(this), "showAddress");
  },
  // 选项发生变化
  async bindChange(e: any): Promise<void> {
    const val = e.detail.value
    const oldVal = this.data.valueTemp
    // 省份变化
    if (oldVal[0] !== val[0]) {
      console.log("省发生了变化")
      this.setData({
        valueTemp: [val[0], 0, 0, 0]
      })
      const province = this.data.provinces[val[0]];
      // 获取对应的市和第一个市对应的区
      await this.getArea('city', province.id)
    }
    // 城市列变化
    else if (oldVal[1] !== val[1]) {
      console.log("市发生了变化")
      this.setData({
        valueTemp: [val[0], val[1], 0, 0]
      })
      const city = this.data.cities[val[1]];
      // 获取对应的区
      await this.getArea('dis', city.id);
    } else if (oldVal[2] !== val[2]) {
      this.setData({
        valueTemp: [val[0], val[1], val[2], 0]
      })
      console.log(val)
      const dis = this.data.districts[val[2]];
      console.log(dis, 'dis')
      await this.getArea('stree', dis.id)
    } else {
      this.setData({
        valueTemp: val,
        isLoading: false
      })
    }
    const province = this.data.provinces[val[0]];
    const city = this.data.cities ? this.data.cities[val[1]] : '';
    const district = this.data.districts ? this.data.districts[val[2]] : '';
    const stree = this.data.strees ? this.data.strees[val[3]] : '';
    if (province) {
      this.setData({
        addressTemp: `${province.name} ${city ? city.name : ''} ${district ? district.name : ''} ${stree ? stree.name : ''}`,
        districtValTemp: stree ? stree : district ? district : city ? city : province
      });
    }
  },
  // 开始滚动
  pickerStart(): void {
    this.setData({
      isLoading: true
    })
  },
  // 确定
  confirm(): void {
    // 正在请求数据，禁止点击
    if (this.data.isLoading) {
      return
    }
    this.setData({
      address: this.data.addressTemp,
      districtVal: this.data.districtValTemp,
      value: this.data.valueTemp
    })
    this.closeAddress();
  },
  // 编辑时获取地区
  async getEditAddress(districts: DistrictModel[]): Promise<void> {
    for (let i = 0; i < districts.length - 1; i++) {
      const district = districts[i];
      const res = await api.district.getDistricts({ parentId: district.id });
      if (res.data.code === '000') {
        // 城市
        if (i == 0) {
          this.setData({
            cities: res.data.data
          })
        }
        // 县
        else if (i == 1) {
          this.setData({
            districts: res.data.data
          })
        } else if (i == 2) {
          this.setData({
            strees: res.data.data
          })
        }
      } else {
        wx.showToast({
          title: res.data.message as string,
          icon: "error",
          duration: 2000
        })
      }
    }
  },
  async fetchData(id: number): Promise<void> {
    let districts: DistrictModel[] = []
    if (id || id == 0) {
      const res = await api.address.getAddressDetail({ id })
      if (res.data.code == "000") {
        if (res.data.data) {
          let address = ''
          if (res.data.data.districts) {
            address = res.data.data.districts.map(item => item.name).join(' ');
            districts = res.data.data.districts
          }
          this.setData({
            isDefault: res.data.data.isDefault,
            detailAddress: res.data.data.detailAddress,
            name: res.data.data.name,
            phone: res.data.data.phone,
            address: address,
            districtVal: districts[districts.length - 1]
          })

        }
      } else {
        wx.showToast({
          title: res.data.message as string,
          icon: "error",
          duration: 2000
        })
      }
    }
    const res = await api.district.getDistricts()
    if (res.data.code == '000') {
      if (res.data.data && res.data.data.length > 0) {
        // 编辑不能请求第一个
        if (id !== 0 && !id) {
          this.getArea('city', res.data.data[0].id);
        }
        this.setData({
          provinces: res.data.data,
        })
        if (id || id == 0) {
          // 根据ID请求
          this.getEditAddress(districts).then(() => {
            const pIndex = this.data.provinces.findIndex(item => {
              return item.id === districts[0].id
            })
            const cIndex = this.data.cities.findIndex(item => {
              return districts[1] && item.id === districts[1].id
            })
            const dIndex = this.data.districts.findIndex(item => {
              return districts[2] && item.id === districts[2].id
            })
            const sIndex = this.data.strees.findIndex(item => {
              return districts[3] && item.id === districts[3].id
            })
            this.setData({
              value: [pIndex, Math.max(0, cIndex), Math.max(0, dIndex), Math.max(0, sIndex)]
            })
          })
        }
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    const id = Number(options.id);
    // 编辑
    if (id || id == 0) {
      this.setData({
        type: 'edit',
        id
      })
    }
    this.fetchData(id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})